﻿using Sunny.UI;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace LEDVANCE.Oscilloscope.VirtualOscilloscope.SavePoints
{
    public class AsyncBoundedChannelList<EntityObjectData>
    {
        private readonly object _lock = new object(); // 用于导出数据时的锁
        private Channel<EntityObjectData> _channel;
        private readonly ConcurrentQueue<EntityObjectData> _buffer = new ConcurrentQueue<EntityObjectData>();
        private  int _capacity;
        private int _currentCount;
        private Task _backgroundTask; // 用于存储后台任务的 Task
        private CancellationTokenSource _cts;

        public AsyncBoundedChannelList(int capacity = 1000)
        {
            _capacity = capacity;
            var options = new BoundedChannelOptions(capacity)
            {
                FullMode = BoundedChannelFullMode.DropOldest,
                SingleWriter = false,
                SingleReader = false
            };

            _channel = Channel.CreateBounded<EntityObjectData>(options);

            _cts = new CancellationTokenSource(); // 初始化 CancellationTokenSource
            _backgroundTask = Task.Run(() => ProcessChannelAsync(_cts.Token));
        }

        private async Task ProcessChannelAsync(CancellationToken cancellationToken = default)
        {
            try
            {
                // 在循环中监听 CancellationToken
                await foreach (var item in _channel.Reader.ReadAllAsync(cancellationToken))
                {
                    Interlocked.Increment(ref _currentCount);
                    _buffer.Enqueue(item);

                    // 如果超过容量，出队最旧的项
                    while (_currentCount >= _capacity)
                    {
                        if (_buffer.TryDequeue(out _))
                        {
                            Interlocked.Decrement(ref _currentCount);
                        }
                    }

                    // 这里可以添加处理数据的逻辑，例如更新UI
                }
            }
            catch (OperationCanceledException)
            {
                // 处理取消操作，可以直接退出循环
                Console.WriteLine("ProcessChannelAsync was canceled.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error processing channel: {ex.Message}");
            }
        }

        public async Task AddAsync(EntityObjectData item, CancellationToken cancellationToken = default)
        {
            try
            {
                await _channel.Writer.WriteAsync(item, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Operation was canceled.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error adding item: {ex.Message}");
            }
        }

        // 导出所有项（线程安全）
        public IEnumerable<EntityObjectData> ExportAllItems()
        {
            lock (_lock)
            {
                return new List<EntityObjectData>(_buffer);
            }
        }
        public async Task ResetAndSetCapacityAsync(int newCapacity)
        {
            CancellationTokenSource localCts = null;

            lock (_lock)
            {
                // 清空缓冲区
                _buffer.Clear();
                _currentCount = 0;

                // 停止现有的后台任务
                localCts = new CancellationTokenSource();
                _cts?.Cancel();

                // 异步等待后台任务完成
                _ = Task.Run(async () =>
                {
                    try
                    {
                        await _backgroundTask;
                    }
                    catch (OperationCanceledException)
                    {
                        // 处理取消操作，如果需要
                        Console.WriteLine("Background task was canceled during ResetAndSetCapacityAsync.");
                    }
                    catch (Exception ex)
                    {
                        // 处理其他可能的异常
                        Console.WriteLine($"Error during ResetAndSetCapacityAsync: {ex.Message}");
                    }
                });

                // 更新容量
                _capacity = newCapacity;

                // 创建新的通道
                var newOptions = new BoundedChannelOptions(newCapacity)
                {
                    FullMode = BoundedChannelFullMode.DropOldest,
                    SingleWriter = false,
                    SingleReader = false
                };
                _channel = Channel.CreateBounded<EntityObjectData>(newOptions);

                // 启动新的后台任务
                _cts = localCts;
                _backgroundTask = Task.Run(() => ProcessChannelAsync(_cts.Token));
            }
        }

    }
}
